<template>
  <div class="updata-photo">
    <img class="img" :src="img" ref="img" />
    <div class="toobar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { updataUserPhoto } from "@/api/user";
export default {
  name: "UpdataPhoto",
  props: {
    img: {
      type: [String, Object],
      required: true,
    },
  },
  data() {
    return {
      cropper: null,
    };
  },
  mounted() {
    const image = this.$refs.img;
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: "move", // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false, // 关闭默认背景
    });
  },
  methods: {
    onConfirm() {
      //基于服务端的裁切 使用 getData 方法获取裁切参数
      // console.log(this.cropper.getData())
      // 纯客户端裁切会用 getCroppedCanvas 获取裁切对象
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        //   错误方法
        // 如果接口 要求 Content-Type 是 application/json
        // 则传递普通JS对象
        // updataUserPhoto({
        //   photo: blob,
        // });
        // 如果接口要求 Content-Type 是multipart/from-data
        // 则你必须传递 FormData对象
        // 创建formData数据
        const formData = new FormData();
        formData.append("photo", blob);
        const { data } = await updataUserPhoto(formData);
        console.log(data);
        this.$emit("close");
        this.$emit("updata-photo", data.data.photo);
      });
    },
  },
};
</script>

<style scoped lang="less">
.updata-photo {
  background-color: #000;
  height: 100%;
  .toobar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      color: #fff;
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .img {
    display: block;
    max-width: 100%;
  }
}
</style>